'use strict';
const express = require('express');
const ejs = require('ejs');
const fs = require('fs');
const path = require('path');
const app = new express(); //实例化,也可以不new 直接 letapp=express();
const formidable = require('formidable');
const xlsx = require('node-xlsx');
const _ = require('lodash');

const TabMap = require('./js/tabMap');
const ObjectMap = require('./js/objMap');

//配置路由
app.get('/', function(req, res) {
  let pathname = req.url;
  if (pathname === '/') {
    pathname = '/index.html'; /*默认加载的首页*/
  }
  if (pathname !== '/favicon.ico') {
    /*过滤请求favicon.ico*/
    ejs.renderFile(`${__dirname}/views/index.ejs`, (err, data) => {
      if (err) {
        console.log(err);
      }
      res.end(data);
    });
  }
});


app.post('/xlsxpost', function(req, res) {
  let pathname = req.url;
  if (pathname !== '/favicon.ico') {
    /*过滤请求favicon.ico*/
    let form = new formidable.IncomingForm();
    form.parse(req, function(err, fields, files) {
      let filePath = files.file.path.replace('\\', '/');
      let sheets = xlsx.parse(filePath);
      let excelArr = removeNullArr(sheets);
      let id = fields.id; // 参数
      for (const TabKey in TabMap.TabMap) {
        let arrayString = [];
        if(id==1){
            arrayString.push('export const');
        }
        const tabMapValue = TabMap.TabMap[TabKey];
        for (let i = 0; i < excelArr.length; i++) {
          const excelItem = excelArr[i];
          if (excelItem.name == tabMapValue.name) {
            let fileString ='';
            let type = ObjectMap.ObjectMap[TabKey].type;
            if(id==1){
              arrayString.push(TabKey);
            }
            let newObjString = '';
            switch (type) {
              case 'data':
                  if(id==1){
                    arrayString.push('= {');
                  }
                arrayString.push(`${id}:{ `);
                arrayString.push(`data: `);
                newObjString = arr2Obj(excelItem.data,TabKey,type);
                arrayString.push(newObjString);
                arrayString.push(` , miaoShu:'' `);
                arrayString.push('},');
                arrayString.push(`}; `);// 加上最后的大括号
                fileString= arrayString.join(' ');
                break;
              case 'list':
                    if(id==1){
                    arrayString.push('= {');
                    }
                    arrayString.push(`${id}: `);
                    newObjString = arr2Obj(excelItem.data,TabKey,type);
                    arrayString.push(newObjString);
                    arrayString.push(",");
                    arrayString.push(`}; `);// 加上最后的大括号
                    fileString= arrayString.join(' ');
                break;
              case 'object':
                if(id==1){
                    arrayString.push('= {');
                }
                arrayString.push(`${id}: `);
                newObjString = arr2Obj(excelItem.data,TabKey,type);
                if(newObjString=='[]'){
                  newObjString='{}'
                }
                arrayString.push(newObjString);
                arrayString.push(",");
                arrayString.push(`}; `);// 加上最后的大括号
                fileString= arrayString.join(' ').replace('[','').replace(']','');

                
                break;
            }
            let filePath = path.resolve(__dirname,`./data/${tabMapValue.fileName}`);
            if(id==1){ // 新文件直接写入
                fs.writeFile(filePath,fileString,(err,data)=>{
                    if(err) throw err;
                });
            }else{ // 追加
                fs.readFile(filePath,(err,data)=>{
                    if(err) throw err;
                    let tempString = data.toString();
                    tempString = tempString.replace('};', '');
                    fs.writeFile(filePath,tempString+fileString,(err,data)=>{
                        if(err) throw err;
                    });
                });
            }
          }
        }

       
        
      }

      // 成功了
      ejs.renderFile(`${__dirname}/views/succeed.ejs`, (err, data) => {
        if (err) {
          console.log(err);
        }
        res.end(data);
      });


    });
  }
});

function removeNullArr(array) {
  let newArr = [];
  for (let i = 0; i < array.length; i++) {
    const datas = array[i].data;
    let evens = _.remove(datas, function(n) {
      return n.length !== 0;
    });
    newArr.push({ name: array[i].name, data: evens });
  }
  return newArr;
}


function arr2Obj(data,TabKey,type){
  let temMapArr = [];
  for (let index = 0; index < data[0].length; index++) {
    for (const objKey in ObjectMap.ObjectMap[TabKey]) {
      const element =data[0][index];
      if (element == ObjectMap.ObjectMap[TabKey][objKey]) {
        temMapArr.push(objKey);
      }
    }
  }

  let newObjArr = [];
  for (let index = 0; index < data.length; index++) {
    let obj = {};
    temMapArr.forEach((o, i) => {
      if (index != 0) {
        if(!data[index][i]&&data[index][i]!=0){
          obj[o]= '';
        }else{
          if((data[index][i]+'').indexOf('%')){
            obj[o] = (data[index][i]+'').replace('%','');
          }else{
            obj[o] = data[index][i];
          }
        }
        if(TabKey=='FUZHAIZISHU'&&o=='jieKuanRiQi'){ // 如果是负债-自述则要加一个年份的字段
          obj['year']=(data[index][i]).toString().substring(0,4);
        }
        if(type=='object'){
          obj['miaoShu']='';
        }
      }
    });
    if (index != 0) {
      newObjArr.push(obj);
    }
  }
  return JSON.stringify(newObjArr);
}


//监听端口
app.listen(8012, '127.0.0.1');
